package com.order.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.order.bean.Order;
import com.order.properties.OrderProperties;
import com.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
//@RequestMapping("/api/order")
//@RefreshScope
public class OrderController {

    @Autowired
    OrderService orderService;

//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;
    @Autowired
    OrderProperties orderProperties;

    @GetMapping("config")
    public String getConfig(){
        return "order.timeout:"+orderProperties.getTimeout()+"；order.auto-confirm:"+orderProperties.getAutoConfirm()
                +"；order.db-url:"+orderProperties.getDbUrl();
    }

    @GetMapping("create")
    public Order createOrder(@RequestParam("productId") Long productId, @RequestParam("userId") Long userId){
        return orderService.createOrder(productId,userId);
    }

    @GetMapping("seckill")
    @SentinelResource(value = "seckill-order",fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "productId",defaultValue = "1000") Long productId,
                         @RequestParam(value = "userId",required = false) Long userId){
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(Long productId, Long userId, Throwable e){
        System.out.println("seckillFallback...");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息："+e.getClass());
        return order;
    }

    @GetMapping("writeDb")
    public String writeDb(){
        return "writeDb success...";
    }

    @GetMapping("readDb")
    public String readDb(){
        log.info("readDb...");
        return "readDb success...";
    }
}
